<?php

namespace App\Http\Middleware;

use App\Models\Admin\Role;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Route;

class AdminRoleMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        $user = Auth::user();
        if($user){
            $userRoles = $user->role;
            if($userRoles){
                $userRoutes=[];
                foreach ($userRoles as $val){
                    $rolePermissions = $val->permission;
                    foreach ($rolePermissions as $v) {
                        $userRoutes[$v->id]=$v->route;
                    }
                }
                if(in_array(Route::currentRouteAction(),$userRoutes)){
                    return $next($request);
                }
            }
        }
        //dd($userRoutes);
        return redirect('/error/noaccess');
    }
}
